﻿using HenrryTools.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace HenrryTools.WinFormTools
{
    public partial class RabbitMQWinForm : Form
    {
        public RabbitMQWinForm()
        {
            InitializeComponent();
        }
        public static string ContentType { get; set; } = "application/json";
        /// <summary>
        /// 查询所有队列的api
        /// </summary>
        public string GetAllQueryUrl { get; set; } = "/api/queues";

        /// <summary>
        /// RabbitmQ
        /// </summary>
        public string RabbitMQIP { get; set; } = "localhost";
        /// <summary>
        /// 账号
        /// </summary>
        public string UserName { get; set; } = "admin";
        /// <summary>
        /// 密码
        /// </summary>
        public string PassWord { get; set; } = "admin";
        /// <summary>
        /// 端口
        /// </summary>
        public string Port { get; set; } = "15672";

        //获取所有队列  get http://localhost:15672/api/queues   Authorization
        //删除所有队列  deelete http://localhost:15672/api/queues/%2F/testa   Authorization
        private void RabbitMQWinForm_Load(object sender, EventArgs e)
        {
            txtIP.Text = RabbitMQIP;
            txtUserName.Text = UserName;
            txtPassWord.Text = PassWord;
            txtPort.Text = Port;
        }
        /// <summary>
        /// 加等待
        /// </summary>
        private void SendQurey()
        {
            if (string.IsNullOrWhiteSpace(txtIP.Text) || string.IsNullOrWhiteSpace(txtPort.Text) || string.IsNullOrWhiteSpace(txtUserName.Text) || string.IsNullOrWhiteSpace(txtPassWord.Text)) {
                labMessage.Text = "IP、端口、账号、密码参数为空，请输入!";
                labMessage.ForeColor = Color.Red;
                return;
            }
            btnTestSend.Text = "请求中";
            btnTestSend.Enabled = false;
            WaitForm1 waitForm1 = new WaitForm1();
            waitForm1.ShowMessage();
            btnSendAsync();
            GetSave();
            waitForm1.HideMessage();
            btnTestSend.Enabled = true;
            btnTestSend.Text = "连接";
        }
        /// <summary>
        /// 获取队列
        /// </summary>
        /// <param name="v"></param>
        private void btnSendAsync()
        {
            try {
                Dictionary<string, string> requestHeaders = new Dictionary<string, string>();
                string UserNamePassWord = Common.HenrryHelper.Base64Encode(Encoding.UTF8, txtUserName.Text + ":" + txtPassWord.Text).Replace(" ", "");
                requestHeaders.Add("Authorization", "Basic " + UserNamePassWord);
                string UrlRoot = string.Format("{0}{1}", "http://" + txtIP.Text + ":" + txtPort.Text, GetAllQueryUrl);
                string response = Common.HttpHelper.CreateRequestWithGET(UrlRoot, requestHeaders, null, Encoding.UTF8, ContentType, null);
                if (string.IsNullOrWhiteSpace(response))
                {
                    labMessage.Text = "连接异常，请检查RabbitMQ的状态";
                    labMessage.ForeColor = Color.Red;
                    return;
                }
                object obj = JsonConvert.DeserializeObject(response);
                DataTable dt = new DataTable();
                dt.Columns.Add("vhost");
                dt.Columns.Add("Name");
                dt.Columns.Add("Message");
                object ArrList = null;
                int nember = 0; int MessageNember = 0;
                foreach (var items in obj as JArray)
                {
                    ArrList = items;
                    var vhost = string.Empty; var Name = string.Empty; var Message = string.Empty;
                    foreach (var item in ArrList as JObject)
                    {
                        if (item.Key == "vhost") vhost = item.Value.ToString();
                        if (item.Key == "name") Name = item.Value.ToString();
                        if (item.Key == "messages") Message = item.Value.ToString();

                    }
                    if (!string.IsNullOrWhiteSpace(vhost) || !string.IsNullOrWhiteSpace(Name) || !string.IsNullOrWhiteSpace(Message))
                    {
                        dataGridView.Rows.Add();
                        dataGridView.Rows[nember].Cells[0].Value = vhost;
                        dataGridView.Rows[nember].Cells[1].Value = Name;
                        dataGridView.Rows[nember].Cells[2].Value = Message;
                        nember++;
                        MessageNember += int.Parse(Message);
                    }
                }
                labMessage.Text = "队列总计:" + nember + " ;消息数量总计:" + MessageNember;
                labMessage.ForeColor = Color.Red;
            } catch (Exception ex) {
                labMessage.Text = "连接异常，请检查RabbitMQ的状态" + ex.Message;
                labMessage.ForeColor = Color.Red;
                return;
            }


        }


        /// <summary>
        /// 调用保存
        /// </summary>
        private void GetSave()
        {
            Properties.Settings.Default.RabbitMQWinForm = txtIP.Text + "," + txtPort.Text + "," + txtUserName.Text + "," + txtPassWord.Text;//保存在Settings
            Properties.Settings.Default.Save();//保存
        }

        /// <summary>
        /// 连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTestSend_Click(object sender, EventArgs e)
        {
            SendQurey();
        }
        /// <summary>
        /// 点击数据行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtIP.Text) || string.IsNullOrWhiteSpace(txtPort.Text) || string.IsNullOrWhiteSpace(txtUserName.Text) || string.IsNullOrWhiteSpace(txtPassWord.Text))
            {
                labMessage.Text = "IP、端口、账号、密码参数为空，请输入!";
                labMessage.ForeColor = Color.Red;
                return;
            }
            var rowIndex = e.RowIndex;
            string Vhost = dataGridView.Rows[rowIndex].Cells["Vhost1"].Value.ToString();
            string Name = dataGridView.Rows[rowIndex].Cells["Name1"].Value.ToString();
            string Message = dataGridView.Rows[rowIndex].Cells["Messages1"].Value.ToString();
            WaitForm1 waitForm1 = new WaitForm1();
            waitForm1.ShowMessage();
            btnQueryDealit(Vhost, Name, Message);
            waitForm1.HideMessage();
        }
        /// <summary>
        /// 查询队列详情
        /// </summary>
        private void btnQueryDealit(string vhost, string name, string message)
        {
            try
            {
                Encoding Encoding = System.Text.Encoding.UTF8;
                Dictionary<string, string> requestHeaders = new Dictionary<string, string>();
                string UserNamePassWord = Common.HenrryHelper.Base64Encode(Encoding.UTF8, txtUserName.Text + ":" + txtPassWord.Text).Replace(" ", "");
                requestHeaders.Add("Authorization", "Basic " + UserNamePassWord);

                Dictionary<string, string> requestPayload = new Dictionary<string, string>();
                requestPayload.Add("ackmode", "ack_requeue_true");
                requestPayload.Add("count", message);
                requestPayload.Add("encoding", "auto");
                requestPayload.Add("name", name);
                requestPayload.Add("truncate", "50000");
                requestPayload.Add("vhost", vhost);
                byte[] dataRoot = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestPayload));

                string UrlRoot = string.Format("{0}{1}", "http://" + txtIP.Text + ":" + txtPort.Text, GetAllQueryUrl + "/" + System.Web.HttpUtility.UrlEncode(vhost, Encoding) + "/" + name + "/get");

                HttpTool client = new HttpTool(UrlRoot);
                object ReturnMsg = client.Exec_Arg_T<Dictionary<string, string>, object>(null, requestPayload, null, "utf-8", false, 60000, requestHeaders);

                //string response = Common.HttpHelper.CreateRequestWithPOST(UrlRoot, requestHeaders, dataRoot, Encoding.UTF8, ContentType, null);
                //if (string.IsNullOrWhiteSpace(response))
                //{
                //    labMessage.Text = "连接异常，请检查RabbitMQ的状态";
                //    labMessage.ForeColor = Color.Red;
                //    return;
                //}
                //object obj = JsonConvert.DeserializeObject(response);
                //DataTable dt = new DataTable();
                //dt.Columns.Add("QueryMessages");
                //object ArrList = null;
                //int nember = 0; 
                //foreach (var items in obj as JArray)
                //{
                //    ArrList = items;
                //    var payload = string.Empty; 
                //    foreach (var item in ArrList as JObject)
                //    {
                //        if (item.Key == "payload") vhost = item.Value.ToString();
                //    }
                //    if (!string.IsNullOrWhiteSpace(payload) )
                //    {
                //        dataGridViewMessages.Rows.Add();
                //        dataGridViewMessages.Rows[nember].Cells[0].Value = payload;
                //        nember++;
                //    }
                //}
            }
            catch (Exception ex)
            {
                labMessage.Text = "连接异常，请检查RabbitMQ的状态" + ex.Message;
                labMessage.ForeColor = Color.Red;
                return;
            }
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            //请查找集合中第一个大于 2147483647 的数--使用二分查找法
            //int i = 1;
            //ulong total = 0;
            //while (total < 2147483647)
            //{
            //    total = seqListNember(i);
            //    i++;
            //}
            MessageBox.Show(seqListNember(47).ToString());
            //MessageBox.Show(Foo2(47).ToString());
            //MessageBox.Show(i.ToString());
        }


        //递归写法
        public  static ulong seqListNember(int Nember)
        {
            ulong X = 1; ulong Y = 1;
            if (Nember == 1 || Nember == 2)
            {
                return 1;
            }
            else
            {
                for (int i = 3; i <= Nember; i++)
                {
                    ulong Z = X + Y; //两数之和
                    Y = X; //之前的和放在b中
                    X = Z; //当前的和放到a中
                }
                return X;
            }
        }
    }
}

